from flask import Blueprint, render_template, redirect, url_for, flash, request
from flask_login import login_user, logout_user, login_required, current_user
from datetime import datetime

from app import db
from app.models.user import User

auth = Blueprint('auth', __name__)

@auth.route('/login', methods=['GET', 'POST'])
def login():
    """登录接口"""
    # 如果已经登录，跳转到主页
    if current_user.is_authenticated:
        return redirect(url_for('main.index'))
    
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        
        user = User.query.filter_by(username=username).first()
        
        # 验证用户名和密码
        if user and user.check_password(password):
            # 验证用户是否为管理员
            if not user.is_admin:
                flash('您不是管理员，无法访问系统!', 'danger')
                return render_template('auth/login.html')
                
            login_user(user)
            user.last_login = datetime.now()
            db.session.commit()
            
            # 跳转到请求的页面，如果存在
            next_page = request.args.get('next')
            if not next_page or not next_page.startswith('/'):
                next_page = url_for('main.index')
                
            flash('登录成功!', 'success')
            return redirect(next_page)
        else:
            flash('登录失败，请检查用户名和密码!', 'danger')
            
    return render_template('auth/login.html')

@auth.route('/logout')
@login_required
def logout():
    """登出接口"""
    logout_user()
    flash('您已成功登出!', 'success')
    return redirect(url_for('auth.login')) 